package com.tiantianyuegou.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.activity.BaseActivity;
import com.tiantianyuegou.R;
import com.tiantianyuegou.adapter.ProductSizeAdapter;
import com.tiantianyuegou.adapter.SetPriceAdapter;
import com.tiantianyuegou.constant.Constant;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.model.ColorOrSizeModel;
import com.tiantianyuegou.model.PriceAndInventoryModel;
import com.tiantianyuegou.model.ProductSizeModel;
import com.tiantianyuegou.model.SelectSpecModel;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.ToastUtilsCenter;
import com.tiantianyuegou.util.Tools;
import com.tiantianyuegou.view.MyDialogEditText;
import com.tiantianyuegou.view.NoScrollListView;
import com.tiantianyuegou.model.PriceAndInventoryModel;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 商品规格
 * Created by ivany on 2016/1/20.
 */
public class ProductSizeActivity extends BaseActivity implements View.OnClickListener {

    private TextView mTxt_sure, mTxt_allSet;
    private NoScrollListView mListView, mSizeList;

    private ProductSizeAdapter mSizeAdapter;
    private List<ProductSizeModel> mSizeData;

    private SetPriceAdapter mListViewAdapter;
    private List<PriceAndInventoryModel> mListData;

    private List<List<SelectSpecModel>> mSelectData;

    private LoadingDialog mLoadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_size);
      Tools.changeSystemBar(this);
        setTitle("商品规格");
        initViews();
    }

    @Override
    public void findViewByIds() {
        mTxt_sure = (TextView) findViewById(R.id.product_size_sure);
        mTxt_allSet = (TextView) findViewById(R.id.product_size_all_set);
        mListView = (NoScrollListView) findViewById(R.id.product_size_statistics);
        mSizeList = (NoScrollListView) findViewById(R.id.product_size_list);
    }

    @Override
    public void initListener() {

        mTxt_allSet.setOnClickListener(this);
        mTxt_sure.setOnClickListener(this);
    }

    @Override
    public void initData() {

        mLoadingDialog = new LoadingDialog(this);
        mSelectData = new ArrayList<>();
        //设置商品的规格
        mSizeData = new ArrayList<>();
        mSizeAdapter = new ProductSizeAdapter(this);
        mSizeList.setAdapter(mSizeAdapter);
        mSizeAdapter.setChangeSelectListener(new ProductSizeAdapter.IChangeSelcetListener() {
            @Override
            public void changeSelect(List<ProductSizeModel> data) {
                setListView(data);
            }
        });
        getProductSize(getIntent().getStringExtra("id"));

        //设置价格和库存
        mListData = new ArrayList<>();
        mListViewAdapter = new SetPriceAdapter(this);
        mListView.setAdapter(mListViewAdapter);
    }

    private void setListView(List<ProductSizeModel> data) {
        //挑选出勾中的规格值
        mSelectData.clear();
        for (int i = 0; i < data.size(); i++) {
            ProductSizeModel model = data.get(i);
            int parentID = model.getSizeId();
            List<SelectSpecModel> list = new ArrayList<>();
            //找出勾选的自定义的规格
            for (int j = 0; j < model.getAddSize().size(); j++) {
                if (model.getAddSize().get(j).isSelect()) {
                    SelectSpecModel specModel = new SelectSpecModel();
                    specModel.setParentID(parentID);
                    specModel.setVlaue("\"" + model.getAddSize().get(j).getLabel() + "\"");
                    list.add(specModel);
                }
            }
            //找出勾选的固定规格
            for (int k = 0; k < model.getFixSize().size(); k++) {
                if (model.getFixSize().get(k).isSelect()) {
                    SelectSpecModel specModel = new SelectSpecModel();
                    specModel.setParentID(parentID);
                    specModel.setVlaue("\"" + model.getFixSize().get(k).getLabel() + "\"");
                    list.add(specModel);
                }
            }
            if (list.size() > 0) {
                mSelectData.add(list);
            }
        }
        if (mSelectData.size() == data.size()) {
            traverseData(mSelectData);
        } else {
            mListData.clear();
//            TODO 需要修改真是参数名称
//            mListViewAdapter.setData(mListData);
            mListViewAdapter.notifyDataSetChanged();
        }
    }

    //遍历数组 ，组合数据（两两组合，两两组合后的数组在和之后一个数组组合，直至最后）
    private void traverseData(List<List<SelectSpecModel>> data) {
        List<SelectSpecModel> resultValues = new ArrayList();//用于存放一次组合的数据
        List<SelectSpecModel> firstData = data.get(0);//第一组数据
        data.remove(0);//移除第一组数据
        if (data.size() > 0) {
            Iterator it = data.iterator();//获得迭代器
            while (it.hasNext()) {//判断是否有下一组数据
                List<SelectSpecModel> nextData = (List<SelectSpecModel>) it.next();//获取下一组数据
                if (nextData.size() > 0) {//判断下一组数据是否不为空
                    for (int i = 0; i < firstData.size(); i++) {//开始遍历组合
                        SelectSpecModel value = firstData.get(i);
                        for (int j = 0; j < nextData.size(); j++) {//
                            SelectSpecModel model = nextData.get(j);
                            SelectSpecModel specModel = new SelectSpecModel();
                            if (value.getAllData() == null || "".equals(value.getAllData())) {//第一次组合时
                                specModel.setAllData(value.getParentID() + "," +
                                        value.getVlaue().substring(1, value.getVlaue().length() - 1) + "," +
                                        model.getParentID() + "," + model.getVlaue().substring(1, model.getVlaue().length() - 1));
                            } else {
                                specModel.setAllData(value.getAllData() + "," +
                                        model.getParentID() + "," + model.getVlaue().substring(1, model.getVlaue().length() - 1));
                            }
                            specModel.setVlaue(value.getVlaue() + "+" + model.getVlaue());
                            resultValues.add(specModel);
                        }
                    }
                    firstData.clear();//将第一组数据清空
                    firstData.addAll(resultValues);//将一次迭代产生的组合赋给第一组list中，进行下次迭代
                    resultValues.clear();//将result数组清空
                }
            }
        } else {//当只有一个规格的时候
            for (int i = 0; i < firstData.size(); i++) {
                firstData.get(i).setAllData(firstData.get(i).getParentID() + "," + firstData.get(i).getVlaue());
            }
        }
        mListData.clear();
        for (int i = 0; i < firstData.size(); i++) {
            PriceAndInventoryModel model = new PriceAndInventoryModel();
            model.setTypeIdS(firstData.get(i).getAllData());
            model.setTypeLabel(firstData.get(i).getVlaue());
            mListData.add(model);
        }
//        TODO 需要换成真正的参数名称
//        mListViewAdapter.setData(mListData);
        mListViewAdapter.notifyDataSetChanged();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.product_size_all_set:
                if (mListData.size() > 0) {
                    MyDialogEditText editTextDialog = new MyDialogEditText(this);
                    editTextDialog.setDialogCallback(new MyDialogEditText.DialogCallback() {
                        @Override
                        public void dialogOpt(String price, String inventry) {
                            if ((price == null || "".equals(price)) || (inventry == null || "".equals(inventry))) {
                                ToastUtilsCenter.makeText(ProductSizeActivity.this, "价格和库存都不能为空", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            if (price.contains(".")) {
                                if (price.substring(price.indexOf(".") + 1).length() > 2) {
                                    ToastUtilsCenter.makeText(ProductSizeActivity.this, "商品价格只能包含两位小数", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                            }
                            for (int i = 0; i < mListData.size(); i++) {
                                mListData.get(i).setPrice(price);
                                mListData.get(i).setInventory(inventry);
                            }
//                            TODO 需换成真正参会苏名称
//                            mListViewAdapter.setData(mListData);
                            mListViewAdapter.notifyDataSetChanged();
                        }
                    });
                    editTextDialog.show();
                } else {
                   ToastUtilsCenter.makeText(this, "请先选择商品的规格", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.product_size_sure:
                boolean hasNull = false;
               /* List<PriceAndInventoryModel> modelList = mListViewAdapter.getData();
                StringBuffer product = new StringBuffer();
                for (int i = 0; i < modelList.size(); i++) {
                    PriceAndInventoryModel model = modelList.get(i);
                    if (model.getPrice() == null || "".equals(model.getPrice()) ||
                            model.getInventory() == null || "".equals(model.getInventory())) {
                        hasNull = true;
                        break;
                    }

                    product.append(model.getPrice()).append(",");
                    product.append(model.getInventory()).append(",");
                    product.append(model.getTypeIdS()).append("|");
                }
                if (hasNull || modelList == null || modelList.size() == 0) {
                    ToastUtilsCenter.makeText(this, "请先设置商品的价格和库存", false).show();
                } else {
                    String productSize = product.toString().substring(0, product.length() - 1);
                    Log.e("TAG", productSize);
                    Intent intent = new Intent();
                    intent.putExtra("productSize", productSize);
                    setResult(Constant.SELECT_SIZE_RESULT, intent);
                    finish();
                }
                break;
                */
        }
    }

    //获取商品规格值列表
    private void getProductSize(String id) {
        mLoadingDialog.setMsg("正在获取商品规格列表");
        mLoadingDialog.show();
        RequestParams params = new RequestParams();
        params.addBodyParameter("categoryId", id);
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.GOODS_SPECIFICATION_LIST, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                mLoadingDialog.dismiss();
                Log.e("TAG", "get productSize response:" + responseInfo.result);
                if (TextUtils.isEmpty(responseInfo.result)) {
                    showMsg("获取商品规格列表失败");
                } else {
                    try {
                        JSONObject root = new JSONObject(responseInfo.result);
                        String code = root.getString("code");
                        if ("100".equals(code)) {
                            JSONArray list = root.getJSONArray("list");
                            if (list.length() > 0) {
                                mSizeData.clear();
                                for (int i = 0; i < list.length(); i++) {
                                    JSONObject value = list.getJSONObject(i);
                                    ProductSizeModel model = new ProductSizeModel();
                                    //解析规格
                                    model.setSizeName(value.getString("tsName"));
                                    model.setSizeId(value.getInt("tsId"));
                                    JSONArray specList = value.getJSONArray("values");
                                    //解析规格值
                                    if (specList.length() > 0) {
                                        List<ColorOrSizeModel> fixData = new ArrayList<ColorOrSizeModel>();
                                        for (int j = 0; j < specList.length(); j++) {
                                            JSONObject specValue = specList.getJSONObject(j);
                                            ColorOrSizeModel specModel = new ColorOrSizeModel();
                                            specModel.setLabel(specValue.getString("tsvValue"));
                                            specModel.setId(specValue.getInt("tsvId"));
                                            specModel.setIsSelect(false);
                                            fixData.add(specModel);
                                        }
                                        model.setFixSize(fixData);
                                    }
                                    List<ColorOrSizeModel> addData = new ArrayList<ColorOrSizeModel>();
                                    model.setAddSize(addData);
                                    mSizeData.add(model);
                                    mSizeAdapter.setData(mSizeData);
                                    mSizeAdapter.notifyDataSetChanged();
                                }
                            } else {
                                showMsg("暂无该商品类型的规格列表");
                            }


                        } else {
                            String msg = root.getString("message");
                            showMsg(msg);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        showMsg("解析异常");
                    }

                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                mLoadingDialog.dismiss();
                Log.e("TAG", "get productSize failure :" + s);
                showMsg("当前网络不可用,请检查您的网络设置");
            }
        });
    }
}
